/*!
 * tykhome - soft.js
 * Author tykhome <yongketian@gmail.com>
 */


var models = require('../models');
var Soft = models.Soft;

var User = require('./user');
var Tag = require('./tag');
var SoftTag = require('./soft_tag');

var Util = require('../libs/util');
var EventProxy = require('eventproxy');


/**
 * 获取所有信息的主题
 * Callback:
 * - err, 数据库异常
 * - message, 消息
 * - soft, 主题
 * - author, 主题作者
 * - tags, 标签
 * @param {String} id 主题ID
 * @param {Function} callback 回调函数
 */
exports.getFullSoft = function (id, callback) {
	var proxy = new EventProxy();
	var events = ['soft', 'author', 'tags'];
	proxy.all(events, function (soft, author, tags) {
		// 第一个参数是err,第二个参数是message
		callback(null, '', soft, author, tags);
	}).fail(callback);

	Soft.findOne({
		_id: id
	}, proxy.done(function (soft) {
		if (!soft) {
			proxy.unbind();
			return callback(null, '此话题不存在或已被删除。');
		}
		proxy.emit('soft', soft);

		User.getUserById(soft.author_id, proxy.done(function (author) {
			if (!author) {
				proxy.emit('author', {
					name: '已注销'
				});
				return;
			}
			proxy.emit('author', author);
		}));

		SoftTag.getSoftTagBySoftId(soft._id, proxy.done(function (soft_tags) {
			if (!soft_tags) {
				proxy.emit('tags', []);
				return;
			}
			var tagIds = [];
			soft_tags.forEach(function (soft_tag) {
				tagIds.push(soft_tag.tag_id)
			});
			Tag.getTagsByIds(tagIds, proxy.done(function (tags) {
				proxy.emit('tags', tags);
			}));
		}));

	}));
};

/**
 * 根据主题ID，查找一条主题
 * @param {String} id 主题ID
 * @param {Function} callback 回调函数
 */
exports.getSoftById = function (id, callback) {
	var proxy = new EventProxy();
	var events = ['soft', 'author', 'tags'];
	proxy.all(events, function(soft, author, tags) {
		return callback(null, soft, author, tags);
	}).fail(callback);

	Soft.findOne({
		_id: id
	}, proxy.done(function (soft) {
		if (!soft) {
			proxy.emit('soft', null);
			proxy.emit('author', null);
			proxy.emit('tags', null);
			return;
		}
		// soft
		proxy.emit('soft', soft);

		// author
		User.getUserById(soft.author_id, proxy.done(function (author) {
			if (!author) {
				proxy.emit('author', {
					name: '已注销'
				});
			}
			proxy.emit('author', author);
		}));

		// tags
		SoftTag.getSoftTagBySoftId(soft._id, proxy.done(function (soft_tags) {
			if (!soft_tags) {
				proxy.emit('tags', []);
			}
			// proxy.after('tag', soft_tags.length, function (tags) {
			// 	proxy.emit('tags', tags);
			// });
			var tagIds = [];
			soft_tags.forEach(function (soft_tag) {
				tagIds.push(soft_tag.tag_id)
			});
			Tag.getTagsByIds(tagIds, proxy.done(function (tags) {
				proxy.emit('tags', tags);
			}));
		}));
	}));

};

exports.getSoftByIds = function (ids, fields, opt, callback) {
	Soft.find({
		_id: {
			'$in': ids
		}
	}, fields, opt, callback);
}

exports.getSoft = function (id, callback) {
	Soft.findOne({
		_id: id
	}, callback);
}

/**
 * 根据关键词，获取主题列表
 * Callback:
 * - err, 数据库错误
 * - count, 主题列表
 * @param {String} query 搜索关键词
 * @param {Object} opt 搜索选项
 * @param {Function} callback 回调函数
 */
exports.getSoftsByQuery = function (query, fields, opt, callback) {
	Soft.find(query, fields, opt, function (err, docs) {
		if (err) {
			return callback(err);
		}
		if (docs.length === 0) {
			return callback(null, []);
		}

		var softs_id = [];
		for (var i = 0; i < docs.length; i++) {
			softs_id.push(docs[i]._id);
		}

		var proxy = new EventProxy();
		proxy.after('soft_ready', softs_id.length, function (softs) {
			// 过滤掉空值
			var filtered = softs.filter(function (item) {
				return !!item;
			});
			return callback(null, filtered);
		});
		proxy.fail(callback);

		softs_id.forEach(function (id, i) {
			exports.getSoftById(id, proxy.group('soft_ready', function (soft, author, tags) {
				// 当id查询出来之后，进一步查询列表时，文章可能已经被删除了
				// 所以这里有可能是null
				if (soft) {
					soft.author = author;
					soft.tags = tags;
					soft.friendly_create_at = Util.format_date(soft.create_at, true);
				}
				return soft;
			}));
		});
	});

};

exports.newAndSave = function (title, abstract, content, html, authorId, callback) {
	var soft = new Soft();
	soft.title = title;
	soft.abstract = abstract;
	soft.content = content;
	soft.author_id = authorId;
	soft.html = html;
	soft.save(callback);
};

exports.updateSoft = function (id, title, content, tags, callback) {
	Soft.update({
		_id: id
	}, {
		$set: {
			title: title,
			abstract: abstract,
			content: content,
			tags: tags
		}
	}, callback);
};